const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors')
const userRouter = require('./routes/admin/UserRouter');
const newsRouter = require('./routes/admin/NewsRouter')
const webNewsRouter = require('./routes/web/NewsRouter')
const productRouter = require('./routes/admin/ProductRouter')
const webProductRouter = require('./routes/web/ProductRouter')
const JWT = require('./utils/jwt');
const app = express();


// 跨域
const allowedOrigins = ['http://127.0.0.1:5173/', 'http://localhost:5173', 'http://127.0.0.1:5174/', 'http://localhost:5174'];
const corsOptions = {
  origin: function (origin, callback) {
    if (allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('不允许的跨域访问'));
    }
  },
};

app.use(express.static('public'));
app.use(cors(corsOptions))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(webNewsRouter)
app.use(webProductRouter)

// token
app.use((req, res, next) => {
  res.header('Access-Control-Expose-Headers', 'Authorization')
  if (req.url === '/adminapi/user/login') {
    next()
    return
  }

  const token = req.headers['authorization'].split(' ')[1]
  if (token) {
    const data = JWT.verify(token)
    if (data) {
      const newToken = JWT.generate({
        _id: data._id,
        password: data.password
      },
        '1d')
      res.header('Authorization', newToken)
      next()
    } else {
      console.log('token过期');
      res.status(401).send({
        code: -1,
        msg: 'token过期'
      })
    }
  }
})

// 路由
app.use(userRouter)
app.use(newsRouter)
app.use(productRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});



// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.send('error');
});

module.exports = app;
